package service.broadcast;

import service.broadcast.MyService.MyBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
	
	private MyBroadcastReceiver myBroadcastReceiver = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        myBroadcastReceiver = new MyBroadcastReceiver();
        
        registerReceiver();
        
        Button binderService = (Button) findViewById(R.id.binderService);
        binderService.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				MainActivity.this.bindService(new Intent(MainActivity.this, MyService.class), mServiceConnection, BIND_AUTO_CREATE);
			}
		});
        
        
        Button unbinderService = (Button) findViewById(R.id.unbinderService);
        unbinderService.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				MainActivity.this.unbindService(mServiceConnection);
			}
		});
        
    }
    
    
    private void registerReceiver(){
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("zekezang.text.receiver");
		MainActivity.this.registerReceiver(myBroadcastReceiver, intentFilter);
	}

    
    private ServiceConnection mServiceConnection = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			MainActivity.this.unregisterReceiver(myBroadcastReceiver);
		}
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
//			System.out.println("ComponentName:"+name);
			MyService.MyBinder myBinder = (MyBinder) service;
			myBinder.getMyService().broadSomething();
		}
	};
}